//
//  My_editViewController.m
//  Bullet
//
//  Created by admin on 2019/8/14.
//  Copyright © 2019 . All rights reserved.
//

#import "My_editViewController.h"
#import "My_editView.h"
#import "My_editTableViewCell.h"
//#import "My_AttestNameViewController.h"
#import "My_editHeaderCell.h"
#import "My_editNickName.h"
#import "HWPanModal.h"
#import "My_editAgeVC.h"
#import "My_editSexVC.h"
#import "My_editIntroVC.h"
#import "TZImagePickerController.h"
#import "My_editAreaVC.h"
@interface My_editViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    My_editView * my_editview;
    NSArray * tipArr;
    NSMutableArray * valueArr;
    NSMutableArray * changeValueArr;
    
    NSArray * ProvinceArr;
    NSArray * CityArr;
    BOOL isselectIndex;
    NSDictionary * pickSelectDic1;
    NSDictionary * pickSelectDic2;
    NSString * pickselectSex;
    
}
@property (strong,nonatomic)My_editHeaderCell * headercell;
@property (assign,nonatomic)BOOL isheaderSeleteImage;
@end

@implementation My_editViewController
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.isheaderSeleteImage){
        self.isheaderSeleteImage = NO;
    }else{
        [my_editview.my_edit_tableView reloadData];
    }
}

-(void)showTextViewNavViewTo1{
    NSMutableArray * showTextViewNavViewNameArrTo1 = [NSMutableArray new];
    UIView * showTextViewNavViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewNavViewViewTo1.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewNavViewViewTo1];
    UILabel * showTextViewNavViewLabelTo1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    NSInteger showTextViewNavViewNumberTo1 = arc4random_uniform(20);
    NSLog(@"：%ld", (long)showTextViewNavViewNumberTo1);
    showTextViewNavViewLabelTo1.text = [NSString stringWithFormat:@"%ld",(long)showTextViewNavViewNumberTo1];
    [showTextViewNavViewLabelTo1 addSubview:showTextViewNavViewLabelTo1];
    
    UIImageView * showTextViewNavViewLabelTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [showTextViewNavViewViewTo1 addSubview:showTextViewNavViewLabelTo2];
    
}
- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = viewback_black;

    my_editview = [[My_editView alloc]initWithFrame:CGRectMake(0, 0, KScreen_W, KScreen_H)];
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:my_editview];
    
    [my_editview.my_edit_tableView registerNib:[UINib nibWithNibName:@"My_editHeaderCell" bundle:nil] forCellReuseIdentifier:@"My_editHeaderCell"];
    my_editview.my_edit_tableView.delegate = self;
    my_editview.my_edit_tableView.dataSource = self;
    my_editview.my_edit_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [my_editview.nav_edit_back addTarget:self action:@selector(my_edit_viewBackTap) forControlEvents:UIControlEventTouchUpInside];
}
-(void)getCityList{
//    [YBNetworking postWithUrl:[HostAddress stringByAppendingFormat:CityList] Dic:nil ISInvalid:NO Suc:^(NSDictionary *data, NSString *code, NSString *msg) {
//        @try {
//            if ([PublicObj JudgmentEmptiness:data Key:@"info"]) {
//                NSArray * arr = data[@"info"];
//                NSArray *sites = [BSiteModel modelsWithData:arr];
//                self->ProvinceArr = [arr[0] objectForKey:@"son"];
//                [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"CityList_save"];
//            }
//        } @catch (NSException *exception) {
//            NSLog(@"getCityList  数据处理报错");
//        }
//        
//        
//    } Fail:^(id fail) {
//        [YBMsgPop showPop:NSLocalizedString(@"网络加载失败", nil)];
//    }];
}
//-(void)getUpdateFields{
//    NSString *saveUrl = [HostAddress stringByAppendingFormat:UpdateFields];
//    saveUrl = [saveUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//}
#pragma mark 表代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 1;
    }else{
        return my_editview.my_edit_tileArr.count;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 260;
    }else{
        if(indexPath.row == 4){
            return 230;
        }
        return 60;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        self.headercell = [tableView dequeueReusableCellWithIdentifier:@"My_editHeaderCell"];
        [self.headercell.headerBg sd_setImageWithURL:KUrlString([QZUserInfoModel share].back_image) placeholderImage:KImageNamed(@"ic_user_bgimage")];
        [self.headercell.faceImage sd_setImageWithURL:KUrlString([QZUserInfoModel share].face) placeholderImage:KImageNamed(@"ic_head_defuls")];
        [self.headercell.changeFace addTarget:self action:@selector(changeFaceTap) forControlEvents:UIControlEventTouchUpInside];
        KWeakSelf
        self.headercell.myEditHeaderBlock = ^(NSInteger index) {
            if(index == 0){
                [weakSelf changeBackTap];
            }else if(index == 1){
                [weakSelf changeFaceTap];
            }
        };
        return self.headercell;
    }else{
        My_editTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"my_cell"];
        if (cell == nil) {
            cell = [[My_editTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"my_cell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.cell_title.text = my_editview.my_edit_tileArr[indexPath.row];
        if(indexPath.row == 0){
            cell.cell_editBtn.hidden = NO;
            cell.cell_value.hidden = NO;
            cell.cell_editBtn_image.hidden = NO;
            cell.cell_remarks_view.hidden = YES;
            if([QZUserInfoModel share].nickname.length == 0){
                cell.cell_value.text = NSLocalizedString(@"请输入昵称", nil);
                cell.cell_value.textColor = COLOR_ALPH(255, 255, 255, 0.6);
            }else{
                cell.cell_value.text = [QZUserInfoModel share].nickname;
                cell.cell_value.textColor = UIColor.whiteColor;
            }
        }else if(indexPath.row == 1){
            cell.cell_editBtn.hidden = NO;
            cell.cell_value.hidden = NO;
            cell.cell_editBtn_image.hidden = NO;
            cell.cell_remarks_view.hidden = YES;
            if([QZUserInfoModel share].sex.length == 0){
                cell.cell_value.text = NSLocalizedString(@"请输入昵称", nil);
                cell.cell_value.textColor = COLOR_ALPH(255, 255, 255, 0.6);
            }else{
                cell.cell_value.text = [QZUserInfoModel share].sex;
                cell.cell_value.textColor = UIColor.whiteColor;
            }
        }else if(indexPath.row == 2){
            cell.cell_editBtn.hidden = NO;
            cell.cell_value.hidden = NO;
            cell.cell_editBtn_image.hidden = NO;
            cell.cell_remarks_view.hidden = YES;
            if([QZUserInfoModel share].birthday.length == 0){
                cell.cell_value.text = NSLocalizedString(@"请选择生日", nil);
                cell.cell_value.textColor = COLOR_ALPH(255, 255, 255, 0.6);
            }else{
                cell.cell_value.text = [QZUserInfoModel share].birthday;
                cell.cell_value.textColor = UIColor.whiteColor;
            }
        }else if(indexPath.row == 3){
            cell.cell_editBtn.hidden = NO;
            cell.cell_value.hidden = NO;
            cell.cell_editBtn_image.hidden = NO;
            cell.cell_remarks_view.hidden = YES;
            if([QZUserInfoModel share].area_str.length == 0){
                cell.cell_value.text = NSLocalizedString(@"请选择地区", nil);
                cell.cell_value.textColor = COLOR_ALPH(255, 255, 255, 0.6);
            }else{
                cell.cell_value.text = [QZUserInfoModel share].area_str;
                cell.cell_value.textColor = UIColor.whiteColor;
            }
        }else if(indexPath.row == 4){
            cell.cell_editBtn.hidden = YES;
            cell.cell_editBtn_image.hidden = YES;
            cell.cell_value.hidden = YES;
            cell.cell_remarks_view.hidden = NO;
            cell.cell_remarks_view.userInteractionEnabled = YES;
            NSString * remarks = [QZUserInfoModel share].motto;
            if (remarks.length != 0) {
                cell.cell_remarks_view.my_remarksTextView.text = remarks;
                cell.cell_remarks_view.my_remarks_numLabel.text = [NSString stringWithFormat:@"%lu/100",(unsigned long)remarks.length];
                cell.cell_remarks_view.my_remarks_tipLabel.hidden = YES;
            }else{
                cell.cell_remarks_view.my_remarks_tipLabel.hidden = NO;
                cell.cell_remarks_view.my_remarksTextView.text = @"";
                cell.cell_remarks_view.my_remarks_numLabel.text = @"0/100";
            }
        }

        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        if(indexPath.row == 0){
            My_editNickName * nick = [[My_editNickName alloc]init];
            [self presentPanModal:nick];
        }else if (indexPath.row == 1){
            My_editSexVC * sex = [[My_editSexVC alloc]init];
            [self presentPanModal:sex];
        }else if (indexPath.row == 2){
            My_editAgeVC* area = [[My_editAgeVC alloc]init];
            [self presentPanModal:area];
        }else if (indexPath.row == 3){
            My_editAreaVC * area = [[My_editAreaVC alloc]init];
            [self presentPanModal:area];
        }else if (indexPath.row == 4){
            My_editIntroVC * intro = [[My_editIntroVC alloc]init];
            [self presentPanModal:intro];
        }
    }
}
#pragma mark 编辑对应事件
-(void)my_edinTap:(UIButton *)sender{
    
}
#pragma mark 返回上一级
-(void)my_edit_viewBackTap{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 编辑资料保存
-(void)my_edit_saveTap{
    NSLog(@"编辑资料保存");
    [self.view endEditing:YES];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([changeValueArr[0] intValue] == 1) {
        [dic setObject:valueArr[0] forKey:@"user_nicename"];
    }
    if ([changeValueArr[1] intValue] == 1) {
        [dic setObject:valueArr[1] forKey:@"sex"];
    }
    if ([changeValueArr[2] intValue] == 1) {
        NSArray * provinceArr = [valueArr[2] componentsSeparatedByString:@" "];
        if (provinceArr.count >=2) {
            [dic setObject:provinceArr[0] forKey:@"province"];
            [dic setObject:provinceArr[1] forKey:@"city"];
        }else if (provinceArr.count == 1){
            [dic setObject:provinceArr[0] forKey:@"province"];
            [dic setObject:@"" forKey:@"city"];
        }
    }
    if ([changeValueArr[4] intValue] == 1) {
        NSString * signature = valueArr[4];
        if (signature.length >0) {
            [dic setObject:valueArr[4] forKey:@"signature"];
        }
    }
    if (dic.count == 0) {
        dic=nil;
        [self my_edit_viewBackTap];
        return;
    }
    NSString *saveUrl;// = [HostAddress stringByAppendingFormat:@"%@&uid=%@&token=%@&fields=%@",UpdateFields,APITool.loginUser.idStr,APITool.loginUser.token,jsonString];
    
//    [YBNetworking postWithUrl:saveUrl Dic:nil ISInvalid:NO Suc:^(NSDictionary *data, NSString *code, NSString *msg) {
//        if ([code isEqual:@"0"]) {
//            [YBMsgPop showPop:@"保存成功"];
//            //刷新个人信息
//            [OverallSituationRequest getUserHomeSuccess:nil];
//            [self my_edit_viewBackTap];
//        }else{
//            if ([code isEqual:@"-1001"]) {
//                [YBMsgPop showPop:msg];
//            }else{
//                [YBMsgPop showPop:data[@"msg"]];
//            }
//        }
//    } Fail:nil];
}
- (void)changeFaceTap{
    TZImagePickerController *imagePickerVc=[[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:nil];
    [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){
        [leftButton setImage:[UIImage imageNamed:@"back_wite"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.needCircleCrop = YES;
    imagePickerVc.scaleAspectFillCrop = YES;
    imagePickerVc.circleCropRadius = KScreen_W/2;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
    imagePickerVc.needShowStatusBar = YES;
    imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithHexString:@"#007AFF"];
    imagePickerVc.naviBgColor = [UIColor whiteColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#007AFF"];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor colorWithHexString:@"#007AFF"];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    KWeakSelf
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if(!photos.count){
            return;
        }
        
        [weakSelf changeFaceOrBackImage:photos[0] isFace:YES];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    weakSelf.isheaderSeleteImage = YES;
}
- (void)changeBackTap{
    TZImagePickerController *imagePickerVc=[[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:nil];
    [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){
        [leftButton setImage:[UIImage imageNamed:@"back_wite"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.needCircleCrop = YES;
    imagePickerVc.scaleAspectFillCrop = YES;
    imagePickerVc.circleCropRadius = KScreen_W/2;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
    imagePickerVc.needShowStatusBar = YES;
    imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithHexString:@"#007AFF"];
    imagePickerVc.naviBgColor = [UIColor whiteColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#007AFF"];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor colorWithHexString:@"#007AFF"];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    KWeakSelf
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if(!photos.count){
            return;
        }
        
        [weakSelf changeFaceOrBackImage:photos[0] isFace:NO];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    weakSelf.isheaderSeleteImage = YES;
}
- (void)changeFaceOrBackImage:(UIImage *)image isFace:(BOOL)isface{
    if(!image){
        return;
    }
    
    [SVProgressHUDTool showWithStatus:nil];
    KMutableDic(sendDic)
    KWeakSelf
    if(isface){
        weakSelf.headercell.faceImage.image = image;
        [sendDic setObject:@"face" forKey:@"key"];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
        [YBNetBase userEditFaceRequest:sendDic fileData:imageData successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
            [SVProgressHUDTool dismiss];
            if(code == 200){
                [[NSUserDefaults standardUserDefaults]setObject:data forKey:QZUserInfoKey];
                /** 给用户单例赋值 */
                [[QZUserInfoModel share] setValuesForKeysWithDictionary:data];
                [[NSUserDefaults standardUserDefaults] synchronize];
//                [self->my_editview.my_edit_tableView reloadData];
            }else{
                [YBMsgPop showPop:msg];
            }
        }];
    }else{
        weakSelf.headercell.headerBg.image = image;
        [sendDic setObject:@"back_image" forKey:@"key"];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
        [YBNetBase userEditbackgroudRequest:sendDic fileData:imageData  successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
            [SVProgressHUDTool dismiss];
            if(code == 200){
                [[NSUserDefaults standardUserDefaults]setObject:data forKey:QZUserInfoKey];
                /** 给用户单例赋值 */
                [[QZUserInfoModel share] setValuesForKeysWithDictionary:data];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }else{
                [YBMsgPop showPop:msg];
            }
        }];
    }
}
-(void)tap{
    [self.view endEditing:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
